package com.webmall.servlet.product;
/**
 * 3用于添加产品的servlet--借助smartupload
 */

import com.jspsmart.upload.*;
import com.webmall.entity.CateEntity;
import com.webmall.entity.ProdEntity;
import com.webmall.service.webmall_CateDao;
import com.webmall.service.webmall_ProdDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet( "/manageHtml/admin_doProdadd")
public class doProdAdd extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //设置字符集
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        //----1创建smartupload对象
        SmartUpload su = new SmartUpload();
        //----2初始化
        su.initialize(this.getServletConfig(),request,response);
        //------3上传过程
        try {
            su.upload();
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
        //------4获取上传的文件对象
        Files files = su.getFiles();
        File f = files.getFile(0);
        //-----5获取上传的文件名,以供传入构造函数
        String fname =f.getFileName();
        //文件进行保存
        try {
            su.save("/images/product");
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }

        //-----获取请求对象
        Request request1 = su.getRequest();
        String pname = request1.getParameter("proName");
        String proCate = request1.getParameter("proCate");
        String proPrice = request1.getParameter("proPrice");
        String proInfo = request1.getParameter("proInfo");
        String proStock = request1.getParameter("proStock");

        //可添加属性验证
        ProdEntity prod = new ProdEntity(0,pname,proInfo,
                Integer.parseInt(proPrice),
                Integer.parseInt(proStock),
                Integer.parseInt(proCate.split("-")[0]),
                Integer.parseInt(proCate.split("-")[1]),
                fname);


        //加入数据库的表中
        int count= webmall_ProdDao.insertProd(prod);


        //成功或失败重定位到哪儿
        if (count >0){
            response.sendRedirect("/manageHtml/admin_productSelect");//成功

        }else {//失败 用输出流输出 js语句
            PrintWriter out = response.getWriter();
            out.write("<script>");
            out.write("alert('产品添加失败');");
            out.write("location.href='manageHtml/admin_prodadd.jsp';");
            out.write("</script>");

        }
    }

}
